package com.greenant.store.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.greenant.store.R;
import com.greenant.store.activity.EditGoodsActivity;
import com.greenant.store.activity.GoodsPerStyleActivity;
import com.greenant.store.activity.MyGoodsActivity;
import com.greenant.store.activity.MyGoodsActivityOld;
import com.greenant.store.adapter.GoodsInfoAdapter;
import com.greenant.store.adapter.GoodsStylesAdapter;
import com.greenant.store.bean.AntAVObject;
import com.greenant.store.bean.AntGoods;
import com.greenant.store.bean.AntGoodsStyles;
import com.greenant.store.bean.GoodsInfo;
import com.greenant.store.bean.GoodsStyles;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class GoodsListFragment extends Fragment {
    private static final String TAG = "GoodsListFragment";
    private Handler handler=null;
    private ListView lv;
    private ArrayList<GoodsInfo> list =new ArrayList<GoodsInfo>();
    private Boolean isShowGoodsStyles;
    private String storeStyle =null;
	private int sectionNum = -1;
    private ArrayList<GoodsStyles> styleList =new ArrayList<GoodsStyles>();
    
    public static GoodsListFragment newInstance(String s,String argv) {
        GoodsListFragment newFragment = new GoodsListFragment();
        Bundle bundle = new Bundle();
        bundle.putString("paraStyle", s);
        bundle.putString("paraValue", argv);
        newFragment.setArguments(bundle);
        return newFragment;       
    }

	@Override
    public void onCreate(Bundle savedInstanceState) {
		isShowGoodsStyles = false;
        super.onCreate(savedInstanceState);  
        Bundle bundle = getArguments();
        getGoodsInfoList(bundle.getString("paraStyle"),bundle.getString("paraValue"));              
    }

    @SuppressLint("HandlerLeak") @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        Log.d(TAG, "TestFragment-----onCreateView");
        View view = inflater.inflate(R.layout.lay_goods_list, container, false);
        lv  = (ListView) view.findViewById(R.id.pull_refresh_list);           
             
        try {
            //handler与线程之间的通信及数据处�?
            handler=new Handler(){
                public void handleMessage(Message msg) {
                    if(msg.what==0){
                        //msg.obj是获取handler发�?�信息传来的数据
                        @SuppressWarnings("unchecked")
                        ArrayList<GoodsInfo> list=(ArrayList<GoodsInfo>) msg.obj;
                        //给ListView绑定数据
                        if (list!=null)
                        {
                        	BinderListData(list);
                        }
                    }else if(msg.what==1){
                        //msg.obj是获取handler发�?�信息传来的数据
                        @SuppressWarnings("unchecked")
                        ArrayList<GoodsStyles> list=(ArrayList<GoodsStyles>) msg.obj;
                        //给ListView绑定数据
                        if (list!=null)
                        {
                        	BinderStylesListData(list);
                        }
                    }
                }
            };
        }catch (Exception e){
            e.printStackTrace();
        }    
        if (isShowGoodsStyles) {
        	lv.setOnItemClickListener(new OnItemClickListener() {
        		
    			@Override
    			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    				//startImagePagerActivity(position)
    				GoodsStyles styleInfo = styleList.get(position);
    				Intent intent = new Intent(getActivity(), GoodsPerStyleActivity.class);
    				intent.putExtra("styleName", styleInfo.getStyles());
    				startActivity(intent);
    			}
    		});
        }else{
        	lv.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					startImagePagerActivity(position);
				}
        	});
        }
        
        return view;
    }
    protected void startImagePagerActivity(int position) {
		Intent intent = new Intent(getActivity(), EditGoodsActivity.class);
		intent.putExtra("goodsinfo", list.get(position));
		startActivity(intent);
	}
    //绑定数据
    private void BinderListData(ArrayList<GoodsInfo> list)
    {
    	 GoodsInfoAdapter hc = GoodsInfoAdapter.newInstance(getActivity().getApplicationContext(),list);
         lv.setAdapter(hc);
         lv.setCacheColorHint(0);
    }  
    
    private void BinderStylesListData(ArrayList<GoodsStyles> list)
    {
    	 GoodsStylesAdapter hc = GoodsStylesAdapter.newInstance(getActivity().getApplicationContext(),list);
         lv.setAdapter(hc);
         lv.setCacheColorHint(0);
    } 
  
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "MyStoreFragment-----onDestroy");
    }
    
	@SuppressLint("SimpleDateFormat") 
	private String getDate(Date d) {
		SimpleDateFormat formatter = new SimpleDateFormat("MM-dd");
		return formatter.format(d);		 
    }
	
	@SuppressLint("SimpleDateFormat") 
	private void getGoodsInfoList(String str,String argv){
		 //AVQuery<AVObject> query = null;
		 if (str.equals(MyGoodsActivityOld.STYLE_ON_SHELF)){	
			 String userId =AVUser.getCurrentUser().getObjectId();
			 AVQuery<AntGoods> query = null;
			 query= AVQuery.getQuery(AntGoods.CLASS_AVGOODS);
			 query.whereEqualTo(AntGoods.ATTR_IS_ON_SHELF, true);
			 query.whereEqualTo(AntGoods.ATTR_USRID, userId);
			 query.whereNotEqualTo(AntGoods.ATTR_FILE, null);
			 query.orderByDescending(AntAVObject.ATTR_UPDATE_AT);
			 doQueryGoodsList(query);
			// relationQueryAll();
		 }else if (str.equals(MyGoodsActivityOld.STYLE_OFF_SHELF)){
			 AVQuery<AntGoods> query = null;
			 query= AVQuery.getQuery(AntGoods.CLASS_AVGOODS);
			 query.whereEqualTo(AntGoods.ATTR_USRID, AVUser.getCurrentUser().getObjectId());
			 query.whereEqualTo(AntGoods.ATTR_IS_ON_SHELF, false);
			 query.whereNotEqualTo(AntGoods.ATTR_FILE, null);
			 query.orderByDescending(AntAVObject.ATTR_UPDATE_AT);
			 doQueryGoodsList(query);
			// relationQueryAll();
		}else if (str.equals(MyGoodsActivityOld.STYLE_GOODS_PERSTYLE)){
			AVQuery<AVObject> query = null;
			 query= AVQuery.getQuery(AntGoods.CLASS_AVGOODS);
			 query.whereEqualTo(AntGoods.ATTR_USRID, AVUser.getCurrentUser().getObjectId());
			 query.whereEqualTo(AntGoods.ATTR_STYLE, argv);
			 query.whereNotEqualTo(AntGoods.ATTR_FILE, null);
			 query.orderByDescending(AntAVObject.ATTR_UPDATE_AT);
			 query.include(AntGoodsStyles.ATTR_RELATION);
			 doQueryGoodsPerStyle(query);
			 //relationQueryAll();
		}else if (str.equals(MyGoodsActivityOld.STYLE_GOODS_STYLES)){

			isShowGoodsStyles = true;
			
			doQueryStylesList();
		}
		
	}
	private void doQueryGoodsList(AVQuery<AntGoods> query){
		 // 限制�?1000条�??
		 query.setLimit(1000);
		 query.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE );
		 query.findInBackground(new FindCallback<AntGoods>() {
			 
		   public void done(List<AntGoods> commentList, AVException e) {
			 
			 if (commentList==null||commentList.size()==0)
				 return;
			 list.clear();
		     for (AntGoods goods : commentList) {
		        GoodsInfo goodsInfo = new GoodsInfo();	
		        //String objectId;        
		       // objectId = new String(goods.getObjectId());
		        goodsInfo.setId(goods.getObjectId());
	        	goodsInfo.setCreateDate(getDate(goods.getUpdatedAt()));
	        	goodsInfo.setDesc(goods.getString(AntGoods.ATTR_DESCRIPTION));	        	
	        	goodsInfo.setUrl(goods.getAVFile(AntGoods.ATTR_FILE).getUrl());
	        	goodsInfo.setPrice(goods.getNumber(AntGoods.ATTR_PRICE).toString());
	        	goodsInfo.setStock(goods.getInt(AntGoods.ATTR_STOCK));
	        	goodsInfo.setSales(goods.getInt(AntGoods.ATTR_TOTAL_SALES));
	        	goodsInfo.setUnit(goods.getString(AntGoods.ATTR_UNIT));
	        	goodsInfo.setStyle(goods.getString(AntGoods.ATTR_STYLE));
	        	goodsInfo.setOnShelf(goods.getBoolean(AntGoods.ATTR_IS_ON_SHELF));
	        	goodsInfo.setDiscount(goods.getDouble(AntGoods.ATTR_DISCOUNT));
	        	list.add(goodsInfo);
		     }
		     handler.sendMessage(handler.obtainMessage(0, list));
		   }
		 });
	}
	
	/*查询商品种类列表*/
	private void doQueryStylesList(){
		 String userIdString =AVUser.getCurrentUser().getObjectId();
				 
		 AVQuery<AVObject> storeInfoQuery = AVQuery.getQuery("StoreInfo");
		 storeInfoQuery.whereEqualTo(AntGoods.ATTR_USRID, userIdString);		 
		 storeInfoQuery.findInBackground(new FindCallback<AVObject>() {
			 
			   public void done(List<AVObject> list, AVException e) {	
				 
			     if (list==null||list.size()==0)
					 return;
			     AVObject storeInfo = list.get(0);
				 storeStyle=storeInfo.getString("storeStyle");
				 sectionNum=storeInfo.getInt("sectionNum");
				 
				 ArrayList<Integer> numbers = new ArrayList<Integer>();
				 numbers.add(0);
				 numbers.add(sectionNum);
				
				 AVQuery<AVObject> query= AVQuery.getQuery(AntAVObject.GOODS_SYTLES_CLASS);
				 				 
				 query.orderByDescending("showIndex");
				 query.setLimit(1000);		
				 query.whereEqualTo("userStyle", storeStyle);
				 query.whereContainedIn("sectionNum", numbers);
				 //query.whereEqualTo("sectionNum", sectionNum);
				 query.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE );
				 query.findInBackground(new FindCallback<AVObject>() {
					 
				   public void done(List<AVObject> commentList, AVException e) {	
					 int count =0;
				     if (commentList==null)
						 return;
				     styleList.clear();
				     for (AVObject style : commentList) {
				    	 GoodsStyles goodsStyle = new GoodsStyles();		       
			        	 goodsStyle.setStyles(style.getString(AntGoodsStyles.ATTR_NAME));  
			        	 
			        	/* AVQuery<AntGoods> countQuery= AVQuery.getQuery(AntAVObject.AVGOODS_CLASS);
			        	 countQuery.setLimit(200);
			        	 countQuery.whereEqualTo(AntGoods.ATTR_STYLE, style.getString(AntGoodsStyles.ATTR_NAME));
			        	 countQuery.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE );
			        	 try {
							count = countQuery.count();
						} catch (AVException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
			        	 goodsStyle.setCount("共"
			        			 +count
			        			 +"件商品");*/
			        	 styleList.add(goodsStyle);
				     }
				     handler.sendMessage(handler.obtainMessage(1, styleList));
				   }
				 });
			   }
			 });
		/* try {
			List<AVObject> list =storeInfoQuery.find();
			
			
		} catch (AVException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}*/
		 // 限制�?1000条�??
		
	}
	
	/*查询每类商品的商品列�?*/
	private void doQueryGoodsPerStyle(AVQuery<AVObject> query){
		 // 限制�?1000条�??
		 query.setLimit(1000);
		 query.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE );
		 query.findInBackground(new FindCallback<AVObject>() {
			 
		   public void done(List<AVObject> commentList, AVException e) {		 
		     if (commentList==null||commentList.size()==0)
				 return;		
	    			
			        if (e != null) {
			          // There was an error
			        } else {
			        	for (AVObject goods : commentList) {
					    	//AVFile avFile = goods.getAVFile("photo");	
					        GoodsInfo goodsInfo = new GoodsInfo();	
					        goodsInfo.setId(goods.getObjectId());
				        	goodsInfo.setCreateDate(getDate(goods.getUpdatedAt()));
				        	goodsInfo.setDesc(goods.getString(AntGoods.ATTR_DESCRIPTION));	        	
				        	goodsInfo.setUrl(goods.getAVFile(AntGoods.ATTR_FILE).getUrl());
				        	goodsInfo.setPrice(goods.getNumber(AntGoods.ATTR_PRICE).toString());
				        	goodsInfo.setStock(goods.getInt(AntGoods.ATTR_STOCK));
				        	goodsInfo.setSales(goods.getInt(AntGoods.ATTR_TOTAL_SALES));
				        	goodsInfo.setUnit(goods.getString(AntGoods.ATTR_UNIT));
				        	goodsInfo.setStyle(goods.getString(AntGoods.ATTR_STYLE));
				        	goodsInfo.setOnShelf(goods.getBoolean(AntGoods.ATTR_IS_ON_SHELF));
				        	goodsInfo.setDiscount(goods.getDouble(AntGoods.ATTR_DISCOUNT));
				        	list.add(goodsInfo);
					     }
			        	handler.sendMessage(handler.obtainMessage(0, list));
			        }
	    	 }	    
		  
		 });
	}
	
	 @Override
	public void onResume() {
	    super.onResume();
	    if (!isShowGoodsStyles){
	    	//GoodsInfoAdapter.notifyDataSetChanged();
	    }
    }
	    
}
